const path = require('path')
const fs = require('fs')

const routerDataSource = [
  {
    id: '4',
    name: 'Tasks',
    title: '任务管理',
    icon: 'iconfont icon-fenzuguanli',
    path: '',
    perm: 'tasks:task:folder',
    children: [
      {
        id: '41',
        name: 'TaskManage',
        title: '任务管理',
        icon: 'iconfont icon-yingjian',
        path: '/tasks/list',
        perm: 'tasks:task:menu',
        component: "() => import('@/views/tasks/TaskList.vue')",
      },
    ],
  },
  {
    id: '5',
    name: 'Cars',
    title: '无人车管理',
    icon: 'iconfont icon-fenzuguanli',
    path: '',
    perm: 'Devices:device:folder',
    children: [
      {
        id: '51',
        name: 'DeviceList',
        title: '设备管理',
        icon: 'iconfont icon-yingjian',
        path: '/devices/device',
        perm: 'devices:device:menu',
        component: "() => import('@/views/devices/DeviceList.vue')",
      },
      {
        id: '52',
        name: 'VideoList',
        title: '视频播放',
        icon: 'iconfont icon-yingjian',
        path: '/devices/video',
        perm: 'devices:video:menu',
        component: "() => import('@/views/devices/VideoList.vue')",
      },
      {
        id: '53',
        name: 'InstructionList',
        title: '历史指令',
        icon: 'iconfont icon-yingjian',
        path: '/devices/instruction',
        perm: 'devices:instruction:menu',
        component: "() => import('@/views/devices/InstructionList.vue')",
      },
      {
        id: '54',
        name: 'Heartbeat',
        title: '心跳日志',
        icon: 'iconfont icon-yingjian',
        path: '/devices/heartbeat',
        perm: 'devices:heartbeat:menu',
        component: "() => import('@/views/devices/HeartbeatList.vue')",
      },
    ],
  },
  {
    id: '6',
    name: 'Takeouts',
    title: '外卖员管理',
    icon: 'iconfont icon-fenzuguanli',
    path: '',
    perm: 'takeouts:takeoutperson:folder',
    children: [
      {
        id: '51',
        name: 'TakeoutPerson',
        title: '外卖员管理',
        icon: 'iconfont icon-yingjian',
        path: '/takeouts/takeoutperson',
        perm: 'takeouts:takeoutperson:menu',
        component: "() => import('@/views/takeouts/TakeoutPersonList.vue')",
      },
    ],
  },
]

const getTemplate = (fileName) => {
  let template = `<template>
  <div class="${fileName}-page">${fileName}-page</div>
  </template>
  <script setup>
  import { ref } from 'vue';

  </script>
  <style lang="scss" scoped>
  </style>
  `
  return template
}
/***
 * 目录操作功能函数 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
 */
const handleDir = (pathStr1) => {
  //切分成数组
  let pathList = pathStr1.split(path.sep)
  let pathStr = ''
  for (let item of pathList) {
    if (!item) {
      continue
    }
    if (item.includes(':')) {
      pathStr += `${item}`
      continue
    }
    pathStr += `/${item}`
    console.log('pathStr11:', pathStr)

    if (hasDir(pathStr)) {
      console.log('hasDir:', pathStr)
      continue
    }
    fs.mkdirSync(pathStr)
  }
}

const hasDir = (path) => {
  if (fs.existsSync(path)) {
    return true
  } else {
    return false
  }
}

/***
 * 目录操作功能函数 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 */

/*****
 * 这个 index.js 功能是将 routes 配置转换为 vue 文件。
 */

function getPathFromImport(importStr) {
  // 使用正则匹配路径部分
  const match = importStr.match(/@\/views(\/[^']+)/)
  return match ? match[1] : null
}

// 定义一个函数，用于将路由菜单转换为Vue文件
const handleRouterMenuToVueFile = (menuList, rootPath) => {
  for (let item of menuList) {
    //那么直接生成对应的目录，以及文件

    if (!item.children) {
      console.log(`item.component: ${item.component}`)
      let fileName1 = getPathFromImport(item.component)
      let pathStr = `${rootPath}/${fileName1}`
      console.log('handleRouterMenuToVueFile', pathStr)
      //解析出来 dir 路径.
      let lastIndex = pathStr.lastIndexOf('/')
      let dirPath = pathStr.substring(0, lastIndex)
      let fileName = pathStr.substring(lastIndex + 1).replace('.vue', '')
      let template = getTemplate(fileName)
      handleDir(dirPath)
      if (fs.existsSync(pathStr)) {
        continue
      }

      fs.writeFileSync(pathStr, template)
      continue
    }

    let children = item.children
    for (let child of children) {
      console.log(
        `child.component: ${typeof child.component},${child.component}`
      )
      let fileName1 = getPathFromImport(child.component)
      let childPathStr = `${rootPath}/${fileName1}`
      // let childPathStr = `${rootPath}/${child.path}.vue`
      //解析出来 dir 路径.
      let childLastIndex = childPathStr.lastIndexOf('/')
      let childDirPath = childPathStr.substring(0, childLastIndex)
      let childFileName = childPathStr
        .substring(childLastIndex + 1)
        .replace('.vue', '')
      let template = getTemplate(childFileName)
      handleDir(childDirPath)
      if (fs.existsSync(childPathStr)) {
        continue
      }
      fs.writeFileSync(childPathStr, template)
    }
  }
}

function getPathFromImport(importStr) {
  // 使用正则匹配路径部分
  const match = importStr.match(/@\/views(\/[^']+)/)
  return match ? match[1] : null
}

//enHance:  增强。
const enHanceRouterDataSource = (filePath, routerList = []) => {
  for (let item of routerList) {
    if (!item.children) {
      item.path = item.path.replace(/\.vue/, '')
      fs.appendFileSync(
        filePath,
        ` {
    id: "${item.id}",
    name: "${item.name}",
    title: "${item.title}",
    icon: "${item.icon}",
    path: "${item.path}",
    perm: "${item.perm}",
    component: "${item.component}"),
 },\n`
      )
      continue
    }

    let children = item.children
    fs.appendFileSync(
      filePath,
      ` {
    id: "${item.id}",
    name: "${item.name}",
    title: "${item.title}",
    icon: "${item.icon}",
    path: "${item.path}",
    perm: "${item.perm}",
    children:[\n`
    )
    enHanceRouterDataSource(filePath, children)

    fs.appendFileSync(filePath, '\n]\n}\n,')
  }
}

const createRouterDataSource = (filePath, routerList = []) => {
  fs.writeFileSync(filePath, 'const routerDataSource = [\n')
  enHanceRouterDataSource(filePath, routerList)
  fs.appendFileSync(filePath, '\n]')
  fs.appendFileSync(filePath, '\nexport default routerDataSource;')
}

const rootPath = path.resolve(__dirname, '..', 'build' + path.sep + 'views')
//判断是否存在 src, view 目录
handleDir(rootPath)
const routesPath = path.resolve(__dirname, '..', 'build' + path.sep + 'routes')
handleDir(routesPath)
createRouterDataSource(
  path.resolve(`${routesPath}`, 'router-data-source.js'),
  routerDataSource
)

handleRouterMenuToVueFile(routerDataSource, rootPath)
